package com.example.music.Utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.Bean.LocalMusicBean;
import com.example.music.R;

public class PlayListDialogFragment extends DialogFragment {
    private LocalMusicAdapter localMusicAdapter;
    private MusicPlaylist mDatas;
    MusicPlayer musicPlayer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.MaterialSearch);
        musicPlayer = MusicPlayer.getInstance();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().setCanceledOnTouchOutside(true);
        View rootView = inflater.inflate(R.layout.play_list_dialog_layout, container, false);

        // 设置宽度为屏宽、靠近屏幕底部。
        final Window window = getDialog().getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);

        //布局设置
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.CLIP_VERTICAL;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);

        //初始化播放列表的对话框
        Context context = getContext();
        mDatas = MusicPlaylist.getInstance();
        Log.d("播放列表",mDatas.getSongs().toString());

        RecyclerView playList = rootView.findViewById(R.id.playListRecyclerView);
        RecyclerView.LayoutManager layoutManager2 = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        playList.setLayoutManager(layoutManager2);

        localMusicAdapter = new LocalMusicAdapter(context, mDatas.getSongs());
        playList.setAdapter(localMusicAdapter);
        localMusicAdapter.notifyDataSetChanged();
        setEventListener();
        return rootView;
    }
    private void setEventListener() {
        /* 设置每一项的点击事件*/
        localMusicAdapter.setOnItemClickListener(new LocalMusicAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                mDatas.setCurrentSongIndex(position);
                LocalMusicBean musicBean = mDatas.getSongs().get(position);
                musicPlayer.addToPlaybackHistory(musicBean);
                musicPlayer.stop();
                musicPlayer.play(musicBean.getPath());
            }
        });
    }

}
